package com.lm.survey.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class XSrreamDateConverter implements Converter {

       

        public XSrreamDateConverter() {
                super();
               
        }

        public boolean canConvert(Class clazz) {
                return java.util.Date.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer,
                        MarshallingContext context) {
                
                Date date = (Date) value;;
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                writer.setValue(formatter.format(date));
        }

        public Object unmarshal(HierarchicalStreamReader reader,
                        UnmarshallingContext context) {
                
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
               
                try {
                        return  formatter.parse(reader.getValue());
                } catch (ParseException e) {
                        throw new ConversionException(e.getMessage(), e);
                }
                
        }
        
        public  static void main(String[] args){
            XStream xStream = new XStream();

            xStream.registerConverter(new XSrreamDateConverter());

            // prints the result
            System.out.println(xStream.toXML(new Date()));

        }

}